package proxy.cglibproxy;

import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

/**
 * @author : DuJiabao
 * @Date : 2021/3/16 14:23
 * @Project : design-pattern
 * @File : null.java
 * @Desc :
 */
public class ProxyFactory implements MethodInterceptor {
  private Object target;

  public ProxyFactory(Object target) {
    this.target = target;
  }

  public Object getProxyInstance() {
    Enhancer enhancer = new Enhancer();
    enhancer.setSuperclass(target.getClass());
    enhancer.setCallback(this);
    return enhancer.create();
  }

  @Override
  public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
    System.out.println("cglib 代理模式 开始");
    Object returnVal = method.invoke(target, objects);   // 反射
    System.out.println("cglib 代理模式 提交");
    return returnVal;
  }
}
